package cn.pconline.autoclub.web.usercenter;

import cn.pconline.autoclub.config.SystemConfig;
import cn.pconline.autoclub.entity.Activity;
import cn.pconline.autoclub.entity.Album;
import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.entity.ClubMember;
import cn.pconline.autoclub.entity.DynaImage;
import cn.pconline.autoclub.entity.DynaInfo;
import cn.pconline.autoclub.entity.DynaPraise;
import cn.pconline.autoclub.entity.DynaReply;
import cn.pconline.autoclub.entity.Photo;
import cn.pconline.autoclub.entity.PhotoReply;
import cn.pconline.autoclub.entity.Subject;
import cn.pconline.autoclub.entity.SubjectDyna;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.entity.UserDyna;
import cn.pconline.autoclub.entity.UserVoted;
import cn.pconline.autoclub.entity.Vote;
import cn.pconline.autoclub.entity.VoteDetail;
import cn.pconline.autoclub.service.ActivityService;
import cn.pconline.autoclub.service.AlbumService;
import cn.pconline.autoclub.service.CensorDynaReplyService;
import cn.pconline.autoclub.service.CensorPhotoReplyService;
import cn.pconline.autoclub.service.ClubService;
import cn.pconline.autoclub.service.DynaIndexService;
import cn.pconline.autoclub.service.EffectiveDynaService;
import cn.pconline.autoclub.service.MemberService;
import cn.pconline.autoclub.service.MessageService;
import cn.pconline.autoclub.service.PhotoPraiseService;
import cn.pconline.autoclub.service.PhotoReplyService;
import cn.pconline.autoclub.service.SubjectDynaService;
import cn.pconline.autoclub.service.SubjectService;
import cn.pconline.autoclub.service.UserService;
import cn.pconline.autoclub.service.UserSubjectService;
import cn.pconline.autoclub.service.VoteService;
import cn.pconline.autoclub.util.AppUtils;
import cn.pconline.autoclub.util.DateUtils;
import cn.pconline.autoclub.util.EncodeUtils;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.StringUtil;
import cn.pconline.autoclub.util.WebUtils;
import cn.pconline.autoclub.util.app.AppControllerStatic;
import cn.pconline.autoclub.web.UserAuth;
import cn.pconline.officialclub.entity.OActivity;
import cn.pconline.officialclub.entity.OClub;
import cn.pconline.officialclub.service.OActivityService;
import cn.pconline.officialclub.service.OClubService;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author zhouruxuan
 * @date 2015年4月15日 下午5:41:03
 */
@Controller
@RequestMapping(value = "/usercenter")
public class UcDynaController {

	@Autowired
	private EffectiveDynaService dynaService;
	@Autowired
	private UserService userService;
	@Autowired
	private ClubService clubService;
	@Autowired
	private SystemConfig systemConfig;
	@Autowired
	private AlbumService albumService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private VoteService voteService;
	@Autowired
	private UserAuth userAuth;
	@Autowired
	private MemberService memberService;
	@Autowired
	private MessageService messageService;
	@Autowired
	private CensorDynaReplyService censorDynaReplyService;
	@Autowired
    private SubjectDynaService subjectDynaService;
    @Autowired
    private UserSubjectService userSubjectService;
	@Autowired
	private OActivityService oActivityService;
    @Autowired
    private OClubService oClubService;
	@Autowired
    private PhotoPraiseService photoPraiseService;
	@Autowired
	private PhotoReplyService photoReplyService;
    @Autowired
    private CensorPhotoReplyService censorPhotoReplyService;
    @Autowired
    private DynaIndexService dynaIndexService;
    @Autowired
    private SubjectService subjectService;
	private static final Logger log = LoggerFactory.getLogger(UcDynaController.class);

	/** 拼接用户头像图片,域名：http://i6.3conline.com/images/upload/upc/face/ */
	private static final long AUTHORPHOTO_URL_I6 = 6L;
    private static final int STRING_LENGTH_300 = 300;//字符串长度
    private static final int DEFAULT_MAX_REPLY_LENGTH = 150;//回复内容最大长度为150
    private static final int DEFAULT_AUTHORPHOTO_SIZE = 50;//作者头像50X50
    private static final int DEFAULT_XSSENCODE = 1; //0 不转, 1 转,默认转
    private static final String APP_API_PARA_XSSENCODE = "xssEncode";//0 原内容 1 过滤xss
    private static final String DEFAULT_USERNAME = "游客";
    /**批量数据最大数**/
    private static final int BATCH_MAX_SIZE = 100;
    /**
     * 根据用户ID获取此用户的动态列表
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/1.0/dyna/getDynaListByUserId.do", method = RequestMethod.GET)
    public void getDynaListByUserId(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        String callback = AppControllerStatic.paramCallback(request);
        int xssEncode = WebUtils.paramInt(request, APP_API_PARA_XSSENCODE, DEFAULT_XSSENCODE);
        long userId = AppControllerStatic.paramUserId(request);
        int pageNo = AppControllerStatic.paramPageNo(request);
        int pageSize = AppControllerStatic.paramPageSize(request);
        

        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();

        //用户参数检查
        if (userId == 0) {
            AppControllerStatic.printErrorMsg(response, "非法参数userId", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        //用户合法检查
        User user = userService.findUser(userId);
        if (user == null) {
            AppControllerStatic.printErrorMsg(response, "此用户不存在", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }

        jsonObject.put("userId", user.getUid());

        //用户个人动态列表
        Pager<DynaInfo> pager = dynaService.getDynaListByUserId(userId, pageNo, pageSize);
        if (pager != null && !pager.getResultList().isEmpty()) {
            for (DynaInfo dynaInfo : pager.getResultList()) {
            	//不返回品牌车友会活动动态
            	if(dynaInfo.getType() == DynaInfo.TYPE_JOIN_ACTIVITY) {
            		continue;
            	}
                JSONObject json = this.toJson4DynaInfo(dynaInfo, xssEncode);
                jsonArray.add(json);
            }
        }

        //返回Json
        jsonObject.put("dynaList", jsonArray);
        AppControllerStatic.printSuccessMsgPager(response, jsonObject, callback, pager, AppControllerStatic.V1_VERSION_LATEST);
    }
    
    /**
     * 组装动态列表的内容，Json格式
     *
     * @param dynaInfo
     * @param xssEncode
     * @return
     */
    private JSONObject toJson4DynaInfo(DynaInfo dynaInfo, int xssEncode) {
        //获取配置文件中的动态切图参数
        int imageQua = systemConfig.getImageQua();

        JSONObject json = new JSONObject();
        json.put("dynaInfoId", dynaInfo.getDynaInfoId());
        //回帖数
        json.put("postCount", dynaInfo.getPostCount());
        //动态发布时间
        json.put("pubTime", dynaInfo.getCreateDate());
        //帖子Title
        json.put("topicTitle", dynaInfo.getTitle() == null ? ""
                : dynaInfo.getTitle());
        //用户ID
        json.put("authorId", dynaInfo.getCreateBy());
        //版块ID
        json.put("forumId", dynaInfo.getForumId());
        json.put("forumName", dynaInfo.getForumName());
        //用户对象
        User user = userService.findUser(dynaInfo.getCreateBy());
        //用户名
        json.put("authorName", user == null ? dynaInfo.getCreateName() : user.getUsername());
        //用户昵称
        String nickName = dynaInfo.getCreateName();
        if (user != null) {
            nickName = user.getNickname() == null ? user.getUsername() : user.getNickname();
        }
        json.put("nickname", nickName);
        //用户头像
        json.put(
                "authorPhoto",
                user == null ? WebUtils.face(0, AppControllerStatic.APP_API_AUTHORPHOTO_SIZE_50, AUTHORPHOTO_URL_I6)
                : WebUtils.face(user.getUid(), AppControllerStatic.APP_API_AUTHORPHOTO_SIZE_50, AUTHORPHOTO_URL_I6));
        //贡献油值
        json.put("contribution", dynaInfo.getPetrol());
        //是否有图片(0:没有，1：有）
        json.put("isHasImg", dynaInfo.getIsPic());
        //是否推荐(0:不是，1：是）
        json.put("isRecommend", dynaInfo.getRecommend());
        //是否为精华帖子（1和2：为精华，0：不是精华）
        json.put("isPick", dynaInfo.getPick());
        //帖子ID
        json.put("topicId", dynaInfo.getTopicId());
        //是否认证
        json.put("isVip", user!=null ? user.getVip():0);
        //点赞数
        json.put("praiseCount", dynaInfo.getPraiseCount());
        //动态图片数组列表
        JSONArray images = new JSONArray();
        List<DynaImage> dynaImages = dynaInfo.getImages();
        
        
        int imgCount = dynaImages.size();
        for (DynaImage dynaImage : dynaImages) {// 获取图片列表信息(URL,width,height必须有值
            if (StringUtils.isBlank(dynaImage.getUrl())) {
                continue;
            }
            /*无宽高，多图时也出; 无宽高单张图时不出*/
            /* if (imgCount == 1 && dynaImage.getWidth() == 0 && dynaImage.getHeight() == 0) {
                break;
            }*/
            JSONObject o = new JSONObject();
            o.put("seq", dynaImage.getSeq());
            o.put("url", AppUtils.converImg(  dynaImage.getUrl(), "_1024x1024", "_120x80"));  // 返回统一格式（现在在个人中心显示）
            o.put("width", dynaImage.getWidth());
            o.put("height", dynaImage.getHeight());
            o.put("qua", imageQua);
            images.add(o);
        }
        
        
        json.put("images", images);
        json.put("dynaType", dynaInfo.getType());
        
        //动态内容
        String content = WebUtils.transformNoBBSFaceThenLimit(dynaInfo.getContent(), STRING_LENGTH_300);
        json.put("content", xssEncode == 0 ? content : EncodeUtils.encodeForHTMLFilterNull(content));
        
        //根据不同动态类型，返回不同的动态内容
        json = this.setDynaJsonByType(json, dynaInfo, dynaInfo.getType(),xssEncode == DEFAULT_XSSENCODE);

        return json;
    }
    
    /**
     * 根据不同动态类型，返回不同的动态列表内容
     * 包括字段:content
     * @param dynaType
     */
    public JSONObject setDynaJsonByType(JSONObject jsonObject, DynaInfo dynaInfo, int dynaType,boolean isXssEncode) {
    	long clubId = dynaInfo.getClubId();//车友会ID
		Club club = clubService.getClub(clubId);//获取车友会
		String clubUrl = club == null ? "" : club.getClubUrl();//车友会域名
		String clubName = club == null ? "" : club.getName();
		String targetUrl = systemConfig.getRoot() + "/" + clubUrl;
//    	String content = EncodeUtils.encodeForHTML(dynaInfo.getContent(), isXssEncode);
    	String content = WebUtils.transformToBBSFace(dynaInfo.getContent());
    	long targetId = dynaInfo.getTargetId();
    	switch (dynaType) {
    	//动态类型1-普通帖子（旧数据包含提问帖子）
    	
		case DynaInfo.TYPE_TOPIC:
			content = WebUtils.transformToBBSFaceThenLimit(dynaInfo.getContent(), STRING_LENGTH_300);
			break;
		//动态类型2-说说动态
		case DynaInfo.TYPE_COMMENT:
			targetId = dynaInfo.getDynaInfoId();
			content = WebUtils.dynaSubjectContent(systemConfig.getRoot(), content, dynaInfo.getSubjectIds() );
			break;
		//动态类型3-图片动态
		case DynaInfo.TYPE_PICTURE:
			Album album = albumService.getAlbumById(targetId);//获取相册
			String albumName = album == null ? "" : album.getName();//相册名字
			//获取上传照片数，内容格式content:{pictureNum:10}
			JSONObject json = JSONObject.parseObject(content);
			int pictureNum = json.getIntValue("pictureNum");
			//组装带有链接的相册提示
			content = "上传了" + pictureNum + "张相片到《" + albumName + "》";
			jsonObject.put("albumName", albumName);
			break;
		//动态类型4-提问帖子
		case DynaInfo.TYPE_QUESTION:
			break;
		//动态类型5-公告动态
		case DynaInfo.TYPE_NOTICE:
			content = "发布了公告：" + content;
			break;
		//动态类型6-活动动态
		case DynaInfo.TYPE_ACTIVITY:
			if (dynaInfo.getIsOfficialClubDyna()==DynaInfo.IS_OFFICIAL) {
				OActivity oActivity=oActivityService.findValidActivity(targetId);
				content = oActivity == null ? "" : EncodeUtils.encodeForHTML(oActivity.getTitle(), isXssEncode);;//活动标题
				String picUrl = oActivity == null ? "" : oActivity.getPicUrl();//活动图片
				//jsonObject.put("picUrl", picUrl);
				jsonObject.put("activityCover", picUrl);
				if(oActivity!=null){
					jsonObject.put("beginDate",oActivity.getBeginDate().getTime());//活动开始时间
					jsonObject.put("endDate", oActivity.getEndDate().getTime());//活动结束时间
					jsonObject.put("signupDate", oActivity.getSignupDate().getTime());//活动截止时间
					jsonObject.put("signUpCount", oActivity.getJoinNum() ); //参加人数
					jsonObject.put("activityCost", oActivity.getMoney() ); //花费
					jsonObject.put("activityPlace", oActivity.getActivityAddress()); //活动地址
					jsonObject.put("maxJoin", oActivity.getMaxJoin()); //活动报名上线人数
					long oClubId = oActivity.getoClubId();
					OClub oClub=oClubService.findValidClub(oClubId);
					clubUrl = oClub == null ? "" : oClub.getUrl();//车友会域名
					jsonObject.put("activityUrl", systemConfig.getRoot()+"/brand/"+clubUrl+"/activity/a"+oActivity.getActivityId()+"/");
				}
			}else{
				Activity activity = activityService.findById(targetId);
				content = activity == null ? "" : EncodeUtils.encodeForHTML(activity.getTitle(), isXssEncode);;//活动标题
				String picUrl = activity == null ? "" : activity.getPicUrl();//活动图片
				//jsonObject.put("picUrl", picUrl);
				jsonObject.put("activityCover", picUrl);
				if(activity!=null){
					jsonObject.put("beginDate",activity.getBeginDate().getTime());//活动开始时间
					jsonObject.put("endDate", activity.getEndDate().getTime());//活动结束时间
					jsonObject.put("signupDate", activity.getSignupDate().getTime());//活动截止时间
					jsonObject.put("signUpCount", activity.getJoinNum() ); //参加人数
					jsonObject.put("activityCost", activity.getMoney() ); //花费
					jsonObject.put("activityPlace", activity.getActivityPlace()); //活动地址
					jsonObject.put("maxJoin", activity.getMaxJoin()); //活动报名上线人数
					jsonObject.put("activityUrl", systemConfig.getRoot()+"/"+clubUrl+"/activity/a"+activity.getActivityId()+"/");
				}
			}
			

			
			break;
		//动态类型7-新会员加入动态
		case DynaInfo.TYPE_JOIN_CLUB:
			content = "Hello，我已经加入了 <a target='_blank' href='"+targetUrl+"'>" + clubName + "</a>，现在我是一个有组织的人了，欢迎大家来围观！";
			jsonObject.put("clubName", clubName );
			break;
		//动态类型8-创建车友会动态
		case DynaInfo.TYPE_CREATE_CLUB:
			content = " 车友会主页：<a target='_blank' href='"+targetUrl+"'>" + targetUrl + "</a>, 大家快去邀请车友加入吧！";
			jsonObject.put("clubName", clubName );
			jsonObject.put("clubUrl", targetUrl );
			break;
		//获取投票人数
		case DynaInfo.TYPE_VOTE:
			Vote vote = voteService.findVoteByVoteId(targetId);
			long voteCount = vote == null ? 0 : vote.getVoteCount();
			jsonObject.put("voteCount", voteCount);
			//投票选项列表
            List<VoteDetail> voteDetails = new ArrayList<VoteDetail>();
            if (vote != null) {
                voteDetails = voteService.listDetailsByVoteId(targetId);
            }
            JSONArray detailArray = new JSONArray();
            for(VoteDetail detail : voteDetails) {
            	JSONObject tempItem = new JSONObject();
	            long voteItemId = detail.getVoteItemId();
	            tempItem.put("itemId", voteItemId );
	            tempItem.put("content", detail.getContent() );
	            tempItem.put("count", detail.getVoteCount() );
	            detailArray.add(tempItem);
            }
            
            jsonObject.put("voteDetail", detailArray);
			break;
		default:
			break;
		}
    	
    	jsonObject.put("dynaTargetId", targetId);
    	jsonObject.put("content", content);
    	return jsonObject;
    }
    
    /**
     * 获取单条动态详情 请求参数：dynaInfoId createBy
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/1.0/dyna/getDynaDetail.do", method = RequestMethod.GET)
    @ResponseBody
    public void getDynaDetail2(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        String callback = AppControllerStatic.paramCallback(request);
        int xssEncode = WebUtils.paramInt(request, APP_API_PARA_XSSENCODE, DEFAULT_XSSENCODE);
        long dynaInfoId = AppControllerStatic.paramDynaInfoId(request);
        long createBy = WebUtils.paramLong(request, "createBy", 0L);

        JSONObject json = new JSONObject();
        JSONArray jsonArray = new JSONArray();

        //获取动态信息
        UserDyna userDyna = dynaService.findUserDynaById(dynaInfoId, createBy);
        if(userDyna == null || userDyna.getStatus() == UserDyna.STATUS_DELETE) {
        	AppControllerStatic.printErrorMsg(response, "动态不存在！", json, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        DynaInfo dynaInfo = dynaService.findDynaById(dynaInfoId, userDyna.getCreateDate());
        if (dynaInfo == null) {
            AppControllerStatic.printErrorMsg(response, "动态不存在！", json, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;

        }

        JSONObject jsonObject = this.toJson4DynaInfo(dynaInfo, xssEncode);
        //返回数据
        jsonArray.add(jsonObject);
        json.put("dynaDetail", jsonArray);
        AppControllerStatic.printSuccessMsg(response, json, callback, AppControllerStatic.V1_VERSION_LATEST);
    }
    
    /**
     * 点赞、取消赞
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/1.0/dyna/doPraise.do", method = RequestMethod.POST)
    public void doPraise(HttpServletRequest request, HttpServletResponse response) {
    	WebUtils.setEncoding( request, response );
    	String originHeader = request.getHeader("Origin");
        if (originHeader != null) {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", originHeader);
        }
        
        
        String callback = AppControllerStatic.paramCallback(request);
        JSONArray praiseDynaInfoIds = WebUtils.parseArray(request, "praiseDynaInfoIds");
        JSONArray unPraiseDynaInfoIds = WebUtils.parseArray(request, "unPraiseDynaInfoIds");
        JSONObject jsonObject = new JSONObject();
        //获取用户登录信息
        User user = userAuth.getUser(request, response);
        if (user == null || user.getUid() == 0) {
            AppControllerStatic.printErrorMsg(response, "用户未登录", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        if (praiseDynaInfoIds == null && unPraiseDynaInfoIds == null) {
            AppControllerStatic.printErrorMsg(response, "参数有误", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        JSONArray failPraiseIds = new JSONArray();
        if (praiseDynaInfoIds != null) {
            for (int i = 0; i < praiseDynaInfoIds.size(); i++) {
                JSONObject obj = null;
                //判断是否转换成功
                try {
                	obj = praiseDynaInfoIds.getJSONObject(i);
                	if (!dynaService.doPraise(user.getUid(), obj.getLong("dynaInfoId"), obj.getDate("createDate"), DynaPraise.STATUS_PRAISE)) {
                        failPraiseIds.add(obj);
                    }	
                } catch(Exception exception) {
                	log.error("[praiseDynaInfoIds] fail to get dynaInfo, data={}", obj);
                	AppControllerStatic.printErrorMsg(response, "参数有误", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
                    return;
                }
            }
        }
        JSONArray failNotPraiseIds = new JSONArray();
        if (unPraiseDynaInfoIds != null) {
            for (int i = 0; i < unPraiseDynaInfoIds.size(); i++) {
                JSONObject obj = null;
                //判断是否转换成功
                try {
                	obj = unPraiseDynaInfoIds.getJSONObject(i);
                	if (!dynaService.doPraise(user.getUid(), obj.getLong("dynaInfoId"), obj.getDate("createDate"), DynaPraise.STATUS_UNPRAISE)) {
                        failNotPraiseIds.add(obj);
                	}
                }catch (Exception e) {
                	log.error("[unPraiseDynaInfoIds] fail to get dynaInfo, data={}", obj);
                	AppControllerStatic.printErrorMsg(response, "参数有误", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
                    return;
                }
            }
        }
        jsonObject.put("time", System.currentTimeMillis());
        if (failPraiseIds.isEmpty() && failNotPraiseIds.isEmpty()) {
            AppControllerStatic.printSuccessMsg(response, jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
        } else {
        	jsonObject.put("failPraiseDynaInfoIds", failPraiseIds);
            jsonObject.put("failUnPraiseDynaInfoIds", failNotPraiseIds);
            AppControllerStatic.printErrorMsg(response, jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
        }
    }
    
    /**
     * 获取动态点赞用户列表
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/1.0/dyna/getPraiseUserList.do", method = RequestMethod.GET)
    public void getPraiseUserList(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        long dynaInfoId = AppControllerStatic.paramDynaInfoId(request);
        int pageNo = AppControllerStatic.paramPageNo(request);
        int pageSize = AppControllerStatic.paramPageSize(request);
        String callback = AppControllerStatic.paramCallback(request);
        
        JSONObject jsonObject = new JSONObject();
        if (dynaInfoId == 0) {
            AppControllerStatic.printErrorMsg(response, "参数有误", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        Pager<User> pager = dynaService.getPraiseUserList(dynaInfoId, pageNo, pageSize);
        JSONArray arr = new JSONArray();
        if (pager != null && !pager.getResultList().isEmpty()) {
        	for (User u : pager.getResultList()) {
                JSONObject obj = new JSONObject();
                long userId = u.getUid();
                obj.put("userId", userId);
                obj.put("nickName", u.getNickname());
                obj.put(
                        "authorPhoto",
                        userId == 0 ? WebUtils.face(0,
                        DEFAULT_AUTHORPHOTO_SIZE) : WebUtils.face(
                        userId, DEFAULT_AUTHORPHOTO_SIZE));
                arr.add(obj);
            }
        }
        jsonObject.put("userList", arr);
        AppControllerStatic.printSuccessMsgPager(response, jsonObject, callback, pager, AppControllerStatic.V1_VERSION_LATEST);
    }

    /**
     * 判断是否已赞
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/1.0/dyna/getHadPraiseList.do", method = RequestMethod.GET)
    public void getHadPraiseList(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        String[] dynaInfoIds = WebUtils.param(request, "dynaInfoIds", "").split(",");
        long userId = AppControllerStatic.paramUserId(request);
        String callback = AppControllerStatic.paramCallback(request);
        
        JSONObject jsonObject = new JSONObject();
        if (userId == 0) {
            AppControllerStatic.printErrorMsg(response, "非法参数userId", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        List<Long> ids = new ArrayList<Long>();
        for (String id : dynaInfoIds) {
            try {
                ids.add(Long.parseLong(id));
            } catch (NumberFormatException e) {
                continue;
            }
        }
        if (ids.isEmpty()) {
            AppControllerStatic.printErrorMsg(response, "非法参数dynaInfoIds", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        
        List<DynaPraise> list = dynaService.listDynaPraise(userId, ids);
        String idString = "";
        for (DynaPraise r : list) {
        	idString = idString + r.getDynainfoId() + ",";
        }
       
        String[] idStrings = {};
        if(!StringUtils.isBlank(idString)){
        	idString = idString.substring(0, idString.length() - 1);
        	idStrings = idString.split(",");
        }
        //字符串数组转Long型数组
        Long[] idLongs = new Long[idStrings.length];
        for(int i=0; i<idStrings.length; i++)
        {
        	idLongs[i] = Long.parseLong(idStrings[i]);
        }
        
        jsonObject.put("hadPraiseList", idLongs);
        AppControllerStatic.printSuccessMsg(response, jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
    }
    
    /**
     * 回复动态
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/1.0/dyna/replyDyna.do", method = RequestMethod.POST)
    public void replyDyna(HttpServletRequest request, HttpServletResponse response) {
    	WebUtils.setEncoding( request, response );
    	String originHeader = request.getHeader("Origin");
        if (originHeader != null) {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", originHeader);
        }
        int windowname = AppControllerStatic.paramWindowName( request );
        String callback = AppControllerStatic.paramCallback(request);
        long dynaInfoId = AppControllerStatic.paramDynaInfoId(request);
        long postToDynaReplyId = WebUtils.paramLong(request, "postToDynaReplyId", 0L);
        int isEncode = NumberUtils.toInt(request.getParameter("isEncode"),0);
        String content = AppControllerStatic.paramContent(request);
        if(isEncode==1){
        	try {
	            content = URLDecoder.decode(content,"UTF-8");
            }
            catch( UnsupportedEncodingException e ) {
	            content = "";
            }
        }
        Date createDate = WebUtils.parseDate(request, "createDate");
        JSONObject jsonObject = new JSONObject();
        
        if (createDate == null || dynaInfoId == 0 || "".equals(content)) {
        	AppControllerStatic.printErrorWithWindowName(response, "非法参数createDate|dynaInfoId|content", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST,windowname);
            return;
        }
        //判断被回复的ID是否存在
        if (postToDynaReplyId > 0L) {
            DynaReply dynaReply = dynaService.findDynaReplyById(postToDynaReplyId, dynaInfoId);
            if (dynaReply == null) {
            	AppControllerStatic.printErrorWithWindowName(response, "非法参数dynaInfoId|postToDynaReplyId", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST,windowname);
                return;
            }
        }

        if (StringUtils.length(content) > DEFAULT_MAX_REPLY_LENGTH) {
        	AppControllerStatic.printErrorWithWindowName(response, "回复内容不能超过" + DEFAULT_MAX_REPLY_LENGTH + "个字符", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST,windowname);
            return;
        }
        User user = userAuth.getUser(request, response);//验证用户是否登录
        if (user == null || user.getUid() == 0) {
        	AppControllerStatic.printErrorWithWindowName(response, "您还没有登陆", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST,windowname);
            return;
        }
        //      ClubMember clubMember = memberService.findMember(user.getUid(), clubId);//验证是否为车友会成员
        DynaInfo dynaInfo = dynaService.findDynaById(dynaInfoId, createDate);//判断动态ID是否正确
        if (dynaInfo == null && postToDynaReplyId == 0L) {
            AppControllerStatic.printErrorWithWindowName(response, "动态ID或者创建时间参数无效!", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST,windowname);
            return;
        }

        DynaReply reply = new DynaReply();
        reply.setContent(content);
        reply.setCreateBy(user.getUid());
        reply.setCreateName(user.getNickname() == null ? user.getUsername() : user.getNickname());
        reply.setDynaInfoId(dynaInfoId);
        reply.setCreateAt(new Date());
        reply.setUpdateAt(new Date());
        reply.setPostToDynaReplyId(postToDynaReplyId);
        if (postToDynaReplyId > 0) {
            DynaReply dynaReply = dynaService.findDynaReplyById(postToDynaReplyId, dynaInfoId);
            if (dynaReply == null) {
            	AppControllerStatic.printErrorWithWindowName(response, "回复ID有误！", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST,windowname);
                return;
            }
            reply.setPostToUserId(dynaReply.getCreateBy());
            reply.setPostToNickName(dynaReply.getCreateName());
            
            jsonObject.put("postToDynaReplyId", postToDynaReplyId);
            jsonObject.put("postToUserId", dynaReply.getCreateBy() );
            jsonObject.put("postToNickName", dynaReply.getCreateName());
        }
        long update = dynaService.replyCommentDyna(reply);
        if (update == 0) {
        	AppControllerStatic.printErrorWithWindowName(response, "操作失败！", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST,windowname);
        } else {
                if (!StringUtils.isBlank(dynaInfo.getSubjectIds())) {   //如果该动态属于某一个话题.(话题动态回复数+1)
                    List<Long> list = dynaInfo.getSubjectList();
                    for(long sId : list){
                        SubjectDyna subjectDyna = subjectDynaService.findSubjectDynaById(sId, dynaInfoId);
	                    if(subjectDyna.getStatus() == SubjectDyna.STATUS_NORMAL){
	                        int count = subjectDyna.getPostCount() + 1;
	                        subjectDyna.setPostCount(count);
	                        subjectDynaService.updateByField(subjectDyna, "post_count");
	                        
	                        //回复话题动态时候，相应的话题回复数+1
	                        Subject subject = subjectService.findSubjectById(sId);
	                        if(subject !=null){
	                        	long sujectReplyCount = subject.getReplyCount() + 1;
	                        	subject.setReplyCount(sujectReplyCount);
	                        	subjectService.updateByField(subject, "reply_count");
	                        }
                       }
                    }
                }
                //返回操作成功的数据信息，用户APP刷新页面显示
                dynaService.updateLastReplyInfo(dynaInfoId, 0L, createDate,
                        reply.getCreateBy(), reply.getCreateName(), reply.getCreateDate());
                reply.setDynaReplyId(update);
                jsonObject.put("postToUserName", reply.getPostToNickName() == null ? "" : reply.getPostToNickName());
                
                jsonObject.put("myIcon", WebUtils.face(reply.getCreateBy(), DEFAULT_AUTHORPHOTO_SIZE));
                jsonObject.put("time", DateUtils.format(reply.getCreateAt(), "MM-dd HH:mm"));
                jsonObject.put("content", WebUtils.transformToBBSFace(reply.getContent()) );
                jsonObject.put("createAt", reply.getCreateAt().getTime());
                jsonObject.put("showCreateDate", DateUtils.format(reply.getCreateAt(), "yyyy-MM-dd"));
                jsonObject.put("showContent", WebUtils.transformToBBSFace(reply.getContent()));
                jsonObject.put("replyId", update);//返回给APP接口
                jsonObject.put("authorPhoto", WebUtils.face(user.getUid(), DEFAULT_AUTHORPHOTO_SIZE));//返回给APP接口
                jsonObject.put("nickname", user.getNickname() == null ? "" : user.getNickname()); //返回给APP接口
                jsonObject.put("postToNickName", reply.getPostToNickName() == null ? "" : reply.getPostToNickName()); //返回给APP接口
                //发送审核平台
                Club club = clubService.getClub(dynaInfo.getClubId());
                if (club != null) {
                    try {
                        censorDynaReplyService.notifyCensorSystemCreate(request, reply, dynaInfo);
                    } catch (Exception e) {
                        log.error("send to conser error:{}", e.getMessage());
                    }
                }
                AppControllerStatic.printSuccessWithWindowName(response,"",jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST,windowname);
                //收到的回复发送
                //品牌车友会的活动动态屏蔽
                if(dynaInfo.getType() != DynaInfo.TYPE_JOIN_ACTIVITY) {
                	dynaService.setJson4BipToListReply(reply, createDate);
                }
            }
    }
    
    
    /**
     * 动态回复列表接口 请求参数：dynaInfoId
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/1.0/dyna/getReplyList.do", method = RequestMethod.GET)
    @ResponseBody
    public void getReplyList(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        String callback = AppControllerStatic.paramCallback(request);
        long dynaInfoId = AppControllerStatic.paramDynaInfoId(request);
        int pageSize = AppControllerStatic.paramPageSize(request);
        int pageNo = AppControllerStatic.paramPageNo(request);
        int source_agent = WebUtils.paramInt(request, "source_agent", 2);
        int descType = WebUtils.paramInt(request, "descType", 1);//0：顺序，1：倒序
        long replyId = WebUtils.paramLong( request, "replyId", 0);
        if(replyId>0){
        	int replyPageNo = dynaService.getReplyPageNo( dynaInfoId, replyId,pageSize ); //根据回复id定位
        	if(replyPageNo>1){
        		pageNo = replyPageNo;
        	}
        }
        JSONObject jsonObject = new JSONObject();
        JSONArray arr = new JSONArray();
        if (dynaInfoId == 0) {
        	AppControllerStatic.printErrorMsg(response, "非法参数dynaInfoId", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        Pager<DynaReply> pager = dynaService.getReplyListByDynaInfoId(dynaInfoId, descType, pageNo, pageSize);
        if (pager != null) {
           // WebUtils.checkPageMaxNo(response, pageNo, pager.getPageCount());
            for (DynaReply info : pager.getResultList()) {
                //根据UserID获取昵称、头像
                User user = userService.findUser(info.getCreateBy());//回复用户
                User postToUser = null;
                if(info.getPostToUserId()>0){
                	postToUser = userService.findUser(info.getPostToUserId());//被回复用户
                }
                JSONObject object = info.getJSONObject(source_agent);
                object.put("authorPhoto", WebUtils.face(info.getCreateBy(), DEFAULT_AUTHORPHOTO_SIZE));
                object.put("nickname", user == null ? DEFAULT_USERNAME : user.getNickname());
                object.put("postToNickName", postToUser == null ? DEFAULT_USERNAME : postToUser.getNickname());
                SimpleDateFormat sdf = new SimpleDateFormat("MM:dd HH:mm:ss");
                object.put("showDate", sdf.format(info.getCreateDate()));
                arr.add(object);
            }
        }
        jsonObject.put("replys", arr);
        jsonObject.put("dynaInfoId", dynaInfoId);
        jsonObject.put("code", AppUtils.STATUS_OK);
        jsonObject.put("message", "成功获取车友会回复列表！");
        AppControllerStatic.printSuccessMsgPager(response, jsonObject, callback, pager, AppControllerStatic.V1_VERSION_LATEST);
    }

    /**
     * 1.1.8 未读动态点赞清零
     * @param request
     * @param response
     */
    @RequestMapping(value = "/1.0/dyna/clearUnreadPraise.do", method = RequestMethod.POST)
    @ResponseBody
    public void clearDynaUnreadPraise(HttpServletRequest request, HttpServletResponse response) {
    	WebUtils.setEncoding( request, response );
        String originHeader = request.getHeader("Origin");
        if (originHeader != null) {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", originHeader);
        }
        String[] dynainfoIds = WebUtils.param(request, "dynaInfoIds", "").split(",");
        JSONObject jsonObject = new JSONObject();
        //获取用户登录信息
        User user = userAuth.getUser(request, response);
        if (user == null || user.getUid() == 0) {
            AppControllerStatic.printErrorMsg(response, "您还没有登陆", jsonObject, null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        List<Long> ids = new ArrayList<Long>(dynainfoIds.length);
        for (String id : dynainfoIds) {
            try {
                ids.add(Long.parseLong(id));
            } catch (java.lang.NumberFormatException e) {
                continue;
            }
        }
        //已赞清零
        List<Long> rs = dynaService.clearUnreadPraise(user.getUid(), ids);
        //去掉重复的动态ID
        HashSet<Long> set = new HashSet<Long>(rs);
        rs.clear();
        rs.addAll(set);
        
        jsonObject.put("successIds", StringUtil.toString(rs.toArray()));
        AppControllerStatic.printSuccessMsg(response, jsonObject, null, AppControllerStatic.V1_VERSION_LATEST);
    }
    
    /**
     * 1.3.1 未读照片点赞清零
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/1.0/photo/clearUnreadPraise.do", method = RequestMethod.POST)
    public void clearPhotoUnreadPraise(HttpServletRequest request, HttpServletResponse response) {
    	WebUtils.setEncoding( request, response );
        String originHeader = request.getHeader("Origin");
        if (originHeader != null) {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", originHeader);
        }
        String[] dynainfoIds = WebUtils.param(request, "photoIds", "").split(",");
        JSONObject jsonObject = new JSONObject();
        //获取用户登录信息
        User user = userAuth.getUser(request, response);
        if (user == null || user.getUid() == 0) {
            AppControllerStatic.printErrorMsg(response, "您还没有登陆", jsonObject, null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        List<Long> ids = new ArrayList<Long>(dynainfoIds.length);
        for (String id : dynainfoIds) {
            try {
                ids.add(Long.parseLong(id));
            } catch (java.lang.NumberFormatException e) {
                continue;
            }
        }
        //已赞清零
        List<Long> rs = photoPraiseService.clearUnreadPraise(user.getUid(), ids);
        //去掉重复的动态ID
        HashSet<Long> set = new HashSet<Long>(rs);
        rs.clear();
        rs.addAll(set);
        
        jsonObject.put("successIds", StringUtil.toString(rs.toArray()));
        AppControllerStatic.printSuccessMsg(response, jsonObject, null, AppControllerStatic.V1_VERSION_LATEST);
    }
    
    /**
     *  1.2.0 用户进行投票接口
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/1.0/vote/takeVote.do", method = RequestMethod.POST)
    public void takeVote(HttpServletRequest request, HttpServletResponse response) {
    	WebUtils.setEncoding( request, response );
        String originHeader = request.getHeader("Origin");
        if (originHeader != null) {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", originHeader);
        }
        //获取相关参数
        String callback = AppControllerStatic.paramCallback(request);
        long voteId = WebUtils.paramLong(request, "voteId", 0);
        long voteItemId = WebUtils.paramLong(request, "voteItemId", 0);
        //获取用户信息
        User user = userAuth.getUser(request, response);
        JSONObject json = new JSONObject();
        //判断用户是否登录
        if (user == null || user.getUid() <= 0) {
            AppControllerStatic.printErrorMsg(response, "您还没有登陆", json, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        long userId = user.getUid();

        //是否加入车友会
        ClubMember clubMember = memberService.findClubMemberByUserId(userId);
        if(clubMember == null) {
        	AppControllerStatic.printErrorMsg(response, "您还没加车友会", json, callback, AppControllerStatic.V1_VERSION_LATEST);
        	return;
        }
              
        //投票信息校验
        Vote vote = voteService.getValidVote(voteId);
        VoteDetail voteDetail = voteService.findVoteDetailByVoteItemId(voteItemId);
        if(vote == null){
       	 AppControllerStatic.printErrorMsg(response, "该投票活动不存在", json, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        if(voteDetail == null){
       	 AppControllerStatic.printErrorMsg(response, "该投票项不存在", json, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        if(vote.getVoteId() != voteDetail.getVoteId()) {
       	 AppControllerStatic.printErrorMsg(response, "该投票活动不存在此选项", json, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        
        //是否本车友会的投票活动
        if(clubMember.getClubId() != vote.getClubId()) {
       	 AppControllerStatic.printErrorMsg(response, "您只能参加本车友会的投票活动", json, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        
        //用户是否已经成功投票过
        UserVoted userVote = voteService.findVoteByUserId(voteId, userId);
        if(userVote != null) {
       	 AppControllerStatic.printErrorMsg(response, "您已经成功投票过，不能重复投票", json, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        
        long result = voteService.createUserVoted(vote, voteDetail, userId);
        
        if(result != 0){
       	 AppControllerStatic.printErrorMsg(response, "投票失败", json, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
             
        AppControllerStatic.printSuccessMsg(response, json, callback, AppControllerStatic.V1_VERSION_LATEST);
   }
    
    /**
     * 1.2.1 删除投票
     * @param request
     * @param response
     */
	@ResponseBody
	@RequestMapping(value = "/1.0/vote/deleteVote.do", method = RequestMethod.POST)
	public void deleteVote(HttpServletRequest request, HttpServletResponse response) {
		WebUtils.setEncoding( request, response );
		String originHeader = request.getHeader("Origin");
        if (originHeader != null) {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", originHeader);
        }
   	   //获取相关参数
       String callback = AppControllerStatic.paramCallback(request);
       long voteId = WebUtils.paramLong(request, "voteId", 0);
       //获取用户信息
       User user = userAuth.getUser(request, response);
       JSONObject jsonObject = new JSONObject();
       //判断用户是否登录
       if (user == null || user.getUid() <= 0) {
           AppControllerStatic.printErrorMsg(response, "您还没有登陆", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
           return;
       }
       //判断投票是否存在
       Vote vote = voteService.getValidVote(voteId);
       if(vote == null) {
       	AppControllerStatic.printErrorMsg(response, "该投票活动不存在", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
           return;
       }
       //判断登录用户是否有删除操作权限--管理员(副会长、会长)，或者投票发布者
       boolean hasDeleteRole;
       long userId = user.getUid();
       if(userId == vote.getCreateBy()){ // 投票创建者
       	hasDeleteRole = true;
       }else{
       	long clubId = vote.getClubId();
       	hasDeleteRole = memberService.isClubNormalAdmin(userId, clubId);
       }
       if(!hasDeleteRole) {
       	AppControllerStatic.printErrorMsg(response, "没有删除权限", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
       	return;
       } 
       //删除投票
       int deleteResult = voteService.deleteVote(voteId);
       //删除车友会投票动态
       if(deleteResult > 0) {
       	DynaInfo dynaInfo = dynaService.findDynaByTypeTargetId(DynaInfo.TYPE_VOTE, voteId, vote.getCreateAt());
       	if(dynaInfo != null) {
       		dynaService.deleteClubDyna(vote.getClubId(), dynaInfo.getDynaInfoId());//删除车友会投票动态
       		dynaService.deleteUserDyna(dynaInfo.getCreateBy(), dynaInfo.getDynaInfoId());//删除个人投票动态
       		dynaIndexService.deleteDynaIndex(dynaInfo.getDynaInfoId());	//删除动态索引表
       	}
       }
       AppControllerStatic.printSuccessMsg(response, jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
	}
	
	/**
	 * 1.2.3 判断用户是否已投票
	 * @param req
	 * @param resp
	 */
    @ResponseBody
    @RequestMapping(value = "/1.0/vote/hasVoted.do", method = RequestMethod.GET)
    public void hasVoted(HttpServletRequest req, HttpServletResponse resp){
    	WebUtils.setEncoding(req, resp);
    	JSONObject json = new JSONObject();
    	String callback = AppControllerStatic.paramCallback(req);
    	long userId = AppControllerStatic.paramUserId(req);
    	long voteId = WebUtils.paramLong( req, "voteId", 0);
    	if(userId<=0){
    		AppControllerStatic.printErrorMsg(resp, "非法参数userId！", json, callback, AppControllerStatic.V1_VERSION_LATEST);
    	}
    	if(voteId<=0){
    		AppControllerStatic.printErrorMsg(resp, "非法参数voteId！", json, callback, AppControllerStatic.V1_VERSION_LATEST);
    	}
    	UserVoted userVote = voteService.findVoteByUserId(voteId, userId);
    	json.put("userId",userId);
		json.put("voteId",voteId);
    	if(userVote!=null){
    		json.put("hasVoted",Vote.HAS_VOTED);
    		json.put("voteItemId", userVote.getVoteItemId());
    	}else{
    		json.put("hasVoted",Vote.NOT_VOTED);
    		json.put("voteItemId", 0);
    	}

    	AppControllerStatic.printSuccessMsg(resp, json, callback, AppControllerStatic.V1_VERSION_LATEST);
    	
    }
    
	/**
	 * 评论照片
	 * @param request
	 * @param response
	 */
	@ResponseBody
    @RequestMapping(value = "/1.0/photo/replyPhoto.do", method = RequestMethod.POST)
	public void replyPhoto(HttpServletRequest request, HttpServletResponse response) {
		WebUtils.setEncoding( request, response );
		String originHeader = request.getHeader("Origin");
        if (originHeader != null) {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", originHeader);
        }
        long albumId = AppControllerStatic.paramAlbumId(request);
        long photoId = AppControllerStatic.paramPhotoId(request);
        String content = AppControllerStatic.paramContent(request);
        int isEncode = NumberUtils.toInt(request.getParameter("isEncode"),0);
        if(isEncode==1){
        	try {
	            content = URLDecoder.decode(content,"UTF-8");
            }
            catch( UnsupportedEncodingException e ) {
	            content = "";
            }
        }
        long postToPhotoReplyId = WebUtils.paramLong(request, "postToPhotoReplyId", 0);
        
        JSONObject jsonObject = new JSONObject();
        
        User user = userAuth.getUser(request, response);
        if(user == null || user.getUid() == User.ANONYMOUS.getUid()) {
            AppControllerStatic.printErrorMsg(response, "您还没有登陆", jsonObject , null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        
        //判断照片是否存在
        Photo photo = albumService.getValidPhoto(photoId, albumId);
        if(photo == null) {
        	AppControllerStatic.printErrorMsg(response, "评论的照片不存在", jsonObject , null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        
        //被回复的评论是否存在
        PhotoReply pr = null;
        if(postToPhotoReplyId > 0) {
        	pr = photoReplyService.findPhotoReplyById(postToPhotoReplyId, photoId);
            if(pr == null) {
            	AppControllerStatic.printErrorMsg(response, "被回复的评论不存在", jsonObject , null, AppControllerStatic.V1_VERSION_LATEST);
                return;
            }
            //不可以回复自己的照片评论
            if(pr.getCreateBy() == user.getUid()) {
            	AppControllerStatic.printErrorMsg(response, "不可以回复自己发表的照片评论", jsonObject , null, AppControllerStatic.V1_VERSION_LATEST);
                return;
            }
        }
        
        if(StringUtils.isEmpty(content)) {
        	AppControllerStatic.printErrorMsg(response, "评论内容不可以为空", jsonObject , null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        
        if(StringUtils.length(content) > 150) {
        	AppControllerStatic.printErrorMsg(response, "评论内容长度不可以超过150", jsonObject , null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        
        //设置照片评论对象
        PhotoReply photoReply = new PhotoReply();
        photoReply.setAlbumId(albumId);
        photoReply.setContent(content);
        photoReply.setCreateAt(new Date());
        photoReply.setCreateBy(user.getUid());
        photoReply.setPhotoId(photoId);
        photoReply.setPostToPhontoReplyId(postToPhotoReplyId);
        //如果直接回复照片，被回复人为照片发布者
        if(postToPhotoReplyId == 0) {
        	photoReply.setPostToUserId(photo.getCreateBy());
        } else {//评论照片者
        	photoReply.setPostToUserId(pr.getCreateBy());
        }
       
        photoReply.setStatus(PhotoReply.STATUS_NORMAL);
        
        //增加照片评论
        long id = photoReplyService.createPhotoReply(photoReply);
        if(id <= 0) {
        	AppControllerStatic.printErrorMsg(response, "评论失败", jsonObject , null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        
        //照片评论数+1
        photoReplyService.updatePhotoClunt(photoId, albumId, 1);
        
        //发送到审核平台
        censorPhotoReplyService.notifyCensorSystemCreate( request, photoReply );
        
        //收到的回复发送
        photoReplyService.setJson4BipToListReply( photoReply, photo );
        AppControllerStatic.printSuccessMsg(response, jsonObject, null, AppControllerStatic.V1_VERSION_LATEST);
	}
	
	/**
	 * 1.1.9 未读已赞数(包括图片赞数，动态赞数)
	 * @param req
	 * @param resp
	 */
    @ResponseBody
    @RequestMapping(value = "/1.0/dyna/getUnReadCount.do", method = RequestMethod.GET)
    public void getUnReadCount(HttpServletRequest req, HttpServletResponse resp){
    	WebUtils.setEncoding(req, resp);
    	String callback = AppControllerStatic.paramCallback(req);
        User user = userAuth.getUser(req, resp);
        JSONObject jsonObject = new JSONObject();
        if(user == null || user.getUid() == User.ANONYMOUS.getUid()) {
            AppControllerStatic.printErrorMsg(resp, "您还没有登陆", jsonObject , callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        //未读数
        jsonObject.put("dynaPraiseNotReadCount", dynaService.getUnReadCount(user.getUid()));
        jsonObject.put("photoPraiseNotReadCount", photoPraiseService.getUnReadCount(user.getUid()));
        AppControllerStatic.printSuccessMsg(resp, jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
    }
    
    /**
     * 获取活动报名人数和投票人数(批量)
     * @param req
     * @param resp
     */
    @ResponseBody
    @RequestMapping(value = "/1.0/dyna/getVoteActivityCount.do", method = RequestMethod.GET)
    public void getVoteActivityCount(HttpServletRequest req, HttpServletResponse resp){
    	WebUtils.setEncoding(req, resp);
    	String callback = AppControllerStatic.paramCallback(req);
    	JSONObject jsonObject = new JSONObject();
    	String activityIds = WebUtils.param(req, "activityIds", "");
    	String voteIds = WebUtils.param(req, "voteIds", "");
    	String[] activityIdArray  = activityIds.split(",");
    	String[] voteIdArray  = voteIds.split(",");
    	if(activityIdArray.length > BATCH_MAX_SIZE){
    		AppControllerStatic.printErrorMsg(resp, "活动id超出最大范围："+BATCH_MAX_SIZE ,jsonObject, callback, AppControllerStatic.V2_VERSION_LATEST);
    		return;
    	}
    	
    	if(voteIdArray.length > BATCH_MAX_SIZE){
    		AppControllerStatic.printErrorMsg(resp, "投票id超出最大范围："+BATCH_MAX_SIZE ,jsonObject, callback, AppControllerStatic.V2_VERSION_LATEST);
    		return;
    	}
    	if(activityIdArray!=null){
    		JSONArray activityArray = new JSONArray();
    		for(String actString:activityIdArray) {
    			JSONObject tempObject = new JSONObject();
    			long activityId = NumberUtils.toLong(actString, 0);
        		if(activityId>0){
        			Activity activity = activityService.findById(activityId);
    	   			 if(activity == null){
    	   				 continue;
    	   			 }
    	   			tempObject.put("activityId", activityId );
    	   			tempObject.put("activityCount", activity.getJoinNum() );
        		}
        		activityArray.add(tempObject);
            }
    		jsonObject.put("activityItems", activityArray );
    	}
    	
    	if(voteIdArray!=null){
    		JSONArray voteArray = new JSONArray();
    		for(String voteString:voteIdArray) {
    			JSONObject tempObject = new JSONObject();
    			long voteId = NumberUtils.toLong(voteString, 0);
    			if(voteId>0){
    				Vote vote = voteService.getValidVote( voteId );
    				if(vote==null){
    					continue;
    				}
    				tempObject.put("voteId", voteId );
    	   			tempObject.put("voteCount", vote.getVoteCount() );
    			}
    			voteArray.add(tempObject);
            }
    		jsonObject.put("voteItems", voteArray );
    	}
    	AppControllerStatic.printSuccessMsg(resp, jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
    	
    }
    
}
